﻿using HDS.IService.Sys;
using HDS.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace HDS.Admin.Api.Middleware
{
    public class AdminActionFilterAttribute : ActionFilterAttribute
    {
        private readonly ISysUserService _isysUserService;

        public AdminActionFilterAttribute(ISysUserService isysUserService)
        {
            _isysUserService = isysUserService;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (IsHaveAllow(filterContext.Filters))
                return;

            var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
            var isDefined = controllerActionDescriptor != null && controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true).Any(a => a.GetType().Equals(typeof(AllowAnonymousAttribute)));
            if (isDefined) 
                return;

            var userId = filterContext.HttpContext.User.FindFirstValue(ClaimTypes.Sid).ObjToInt();
            if (userId > 0)
            {
                var task = _isysUserService.HasFun(userId, filterContext.HttpContext.Request.Path);
                task.Wait();
                if (task.Result)
                    return;
                else
                    filterContext.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            }
            else
            {
                filterContext.HttpContext.Response.StatusCode = StatusCodes.Status403Forbidden;
            }

            filterContext.HttpContext.Response.ContentType = "application/json;charset=utf-8";
            filterContext.Result = new JsonResult(new ResultData<string>
            {
                Success = false,
                Code = ErrorCode.Unauthorized,
                Message = "Action unauthorized"
            });

            base.OnActionExecuting(filterContext);
        }


        //判断是否不需要权限
        public static bool IsHaveAllow(IList<IFilterMetadata> filers)
        {
            for (int i = 0; i < filers.Count; i++)
            {
                if (filers[i] is IAllowAnonymousFilter || filers[i] is IAllowAnonymous)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
